use serde::{Deserialize, Serialize};
use serialport::{Error, SerialPortInfo};

pub fn list_serial() -> Result<Vec<SerialPortInfo>, Error> {
    let serial_port_info = serialport::available_ports()?;
    Ok(serial_port_info)
}

#[derive(Serialize, Deserialize)]
pub struct USBPortInfo {
    serial_name: String,
    product: String,
}

pub fn list_serial_info(serial_type: serialport::SerialPortType) -> Result<String, Error> {
    let mut serial_ports: Vec<USBPortInfo> = Vec::new();
    let serial_port_list = list_serial().unwrap();

    for port in serial_port_list {
        match port.port_type {
            t if t == serial_type => {
                serial_ports.push(USBPortInfo {
                    serial_name: port.port_name,
                    product: "".to_owned(),
                });
            }
            _ => {
                // serial_ports.push(_.)
            }
        }
    }

    let _data = serde_json::to_string(&serial_ports).unwrap();
    Ok(_data)
}

pub fn list_usb_info() -> Result<String, Error> {
    let mut usb_ports: Vec<USBPortInfo> = Vec::new();
    let serial_port_list = list_serial().unwrap();
    for port in serial_port_list {
        match port.port_type {
            serialport::SerialPortType::UsbPort(info) => {
                usb_ports.push(USBPortInfo {
                    serial_name: port.port_name,
                    product: match info.product {
                        Some(x) => x, // 获取产品名称
                        None => "Unknown".to_string(),
                    },
                })
            }
            _ => {}
        }
    }

    let _data = serde_json::to_string(&usb_ports).unwrap();
    Ok(_data)
}
